﻿using System;
using System.IO.IsolatedStorage;
using System.Text;
using System.IO;

namespace E_Surfing.WP8Framework
{
    /// <summary>
    /// 文件类
    /// author:caiwb
    /// data:2011-09-18
    /// </summary>
    public class WPFile
    {
        public WPFile()
        {
            
        }

        /// <summary>
        /// 在独立存储区中创建文件
        /// </summary>
        /// <param name="fileName">要在独立存储区中创建的文件的相对路径 名字</param>
        /// <returns></returns>
        public void CreateFile(string fileName)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream rootFile = store.CreateFile(fileName))
                    {
                        rootFile.Close();
                    }
                    store.Dispose();
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 在独立存储区中创建文件
        /// </summary>
        /// <param name="dirName">目录</param>
        /// <param name="fileName"></param>
        public void CreateFile(string dirName, string fileName)
        {
            if (!DirectoryExist(dirName))
            {
                CreateDirectory(dirName);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);

            CreateFile(sb.ToString());
        }

        /// <summary>
        /// 在独立存储范围中创建目录
        /// </summary>
        /// <param name="dirName"></param>
        public void CreateDirectory(string dirName)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!store.DirectoryExists(dirName))
                    {
                        store.CreateDirectory(dirName);
                    }
                    store.Dispose();
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 删除独立存储范围中的目录 && 删除目录里的所有文件 目前不支持目录里还有目录的删除
        /// </summary>
        /// <param name="dirName">要在独立存储范围中删除的目录的相对路径</param>
        public void DeleteDirectory(string dirName)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.DirectoryExists(dirName))
                    {
                        //删除子文件
                        foreach (string file in store.GetFileNames(dirName + "/*"))
                        {
                            store.DeleteFile(dirName + "\\" + file);
                        }
                        store.DeleteDirectory(dirName);
                    }
                    store.Dispose();
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 删除独立存储区中的文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public void DeleteFile(string fileName)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (FileExist(fileName))
                    {
                        store.DeleteFile(fileName);
                    }
                    store.Dispose();
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 删除独立存储区中的文件
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileName"></param>
        public void DeleteFile(string dirName, string fileName)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);
            DeleteFile(sb.ToString());
        }

        /// <summary>
        /// 确定指定的路径是否指的是独立存储区中的现有文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool FileExist(string fileName)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    bool bFileExists = store.FileExists(fileName);
                    store.Dispose();
                    return bFileExists;
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 确定指定的路径是否指的是独立存储区中的现有文件
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool FileExist(string dirName, string fileName)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);

            return FileExist(sb.ToString());
        }

        /// <summary>
        /// 删除独立存储范围中的目录
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public bool DirectoryExist(string dirName)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    bool bDirExists = store.DirectoryExists(dirName);
                    store.Dispose();
                    return bDirExists;
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 在指定的模式中打开文件 用于写
        /// </summary>
        /// <param name="path"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public IsolatedStorageFileStream OpenFileForWrite(string path, FileMode mode)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    return store.OpenFile(path, mode, FileAccess.Write);
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 在指定的模式中打开文件 用于读
        /// </summary>
        /// <param name="path"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public IsolatedStorageFileStream OpenFileForRead(string path, FileMode mode)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    return store.OpenFile(path, mode, FileAccess.Read);
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 在指定的模式中打开文件 用于读写
        /// </summary>
        /// <param name="path"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public IsolatedStorageFileStream OpenFileForReadWrite(string path, FileMode mode)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    return store.OpenFile(path, mode, FileAccess.ReadWrite);
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 将IsolatedStorageFileStream对象偏移
        /// </summary>
        /// <param name="path"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public long SeekFilePosition(ref IsolatedStorageFileStream isoStream, long offset)
        {
            try
            {
                long pos = isoStream.Seek(offset, SeekOrigin.Current);
                isoStream.Close();
                return pos;
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 使用从字节数组中读取的数据将字节块写入 IsolatedStorageFileStream 对象
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public bool WriteStreamToFile(string fileName, byte[] bytes)
        {
            try
            {
                using (IsolatedStorageFileStream myStream = OpenFileForWrite(fileName, FileMode.OpenOrCreate))
                {
                    if (null != myStream)
                    {
                        myStream.Write(bytes, 0, bytes.Length);
                        myStream.Close();
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 使用从字节数组中读取的数据将字节块写入 IsolatedStorageFileStream 对象
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        public bool WriteStreamToFile(string dirName, string fileName, byte[] bytes)
        {
            if (!DirectoryExist(dirName))
            {
                CreateDirectory(dirName);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);

            return WriteStreamToFile(sb.ToString(), bytes);
        }
            
        /// <summary>
        /// 使用从string块写入 IsolatedStorageFileStream 对象
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public bool WriteStringToFile(string fileName, string strData)
        {
            try
            {
                byte[] byteArray = Encoding.Unicode.GetBytes(strData);
                using (IsolatedStorageFileStream myStream = OpenFileForWrite(fileName, FileMode.OpenOrCreate))
                {
                    if (null != myStream)
                    {
                        myStream.Write(byteArray, 0, byteArray.Length);
                        myStream.Close();
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// hrc
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public bool WriteStreamToNewFile(string fileName, byte[] bytes)
        {
            try
            {
                using (IsolatedStorageFileStream myStream = OpenFileForWrite(fileName, FileMode.Create))
                {
                    if (null != myStream)
                    {
                        myStream.Write(bytes, 0, bytes.Length);
                        myStream.Close();
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 使用从字节数组中读取的数据将字节块写入 IsolatedStorageFileStream 对象
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        public bool WriteStringToFile(string dirName, string fileName, string strData)
        {
            if (!DirectoryExist(dirName))
            {
                CreateDirectory(dirName);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);

            return WriteStringToFile(sb.ToString(), strData);
        }

        /// <summary>
        /// 使用从字节数组中读取的数据将字节块写入 IsolatedStorageFileStream 对象
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        public bool AppendStreamToFile(string fileName, byte[] bytes)
        {
            try
            {
                if (FileExist(fileName))
                {
                    using (IsolatedStorageFileStream myStream = OpenFileForWrite(fileName, FileMode.Append))
                    {
                        if (myStream != null)
                        {
                            myStream.Write(bytes, 0, bytes.Length);
                            myStream.Close();
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 使用从字节数组中读取的数据将字节块写入 IsolatedStorageFileStream 对象
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        public bool AppendStreamToFile(string dirName, string fileName, byte[] bytes)
        {
            if (!DirectoryExist(dirName))
            {
                CreateDirectory(dirName);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);

            return AppendStreamToFile(sb.ToString(), bytes);
        }

        /// <summary>
        /// 使用从字节数组中读取的数据将字节块写入 IsolatedStorageFileStream 对象
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        public bool AppendStringToFile(string fileName, string strData)
        {
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(strData);
                if (FileExist(fileName))
                {
                    using (IsolatedStorageFileStream myStream = OpenFileForWrite(fileName, FileMode.Append))
                    {
                        if (myStream != null)
                        {
                            myStream.Write(bytes, 0, bytes.Length);
                            myStream.Close();
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 使用从字节数组中读取的数据将字节块写入 IsolatedStorageFileStream 对象
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        public bool AppendStringToFile(string dirName, string fileName, string strData)
        {
            if (!DirectoryExist(dirName))
            {
                CreateDirectory(dirName);
            }

            StringBuilder sb = new StringBuilder();
            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);

            return AppendStringToFile(sb.ToString(), strData);
        }

        /// <summary>
        /// 将字节从当前缓冲的 IsolatedStorageFileStream 对象复制到数组
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        public bool ReadStreamFromFile(string fileName, ref byte[] buffer, int offset, int count)
        {
            try
            {
                if (FileExist(fileName))
                {
                    using (IsolatedStorageFileStream myStream = OpenFileForRead(fileName, FileMode.Open))
                    {
                        if (myStream != null)
                        {
                            myStream.Read(buffer, offset, count);
                            myStream.Close();
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 将字节从当前缓冲的 IsolatedStorageFileStream 对象复制到数组
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileName"></param>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        public bool ReadStreamFromFile(string dirName, string fileName, ref byte[] buffer, int offset, int count)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);

            return ReadStreamFromFile(sb.ToString(), ref buffer, offset, count);
        }

        /// <summary>
        /// 将字节从当前缓冲的 IsolatedStorageFileStream 对象复制到数组
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        public bool ReadStringFromFile(string fileName, ref string strData)
        {
            try
            {
                if (FileExist(fileName))
                {
                    using (IsolatedStorageFileStream myStream = OpenFileForRead(fileName, FileMode.Open))
                    {
                        long lSize = myStream.Length;
                        int iMax = 65535;
                        int readSize = (int)lSize;

                        do
                        {
                            if(lSize > iMax)
                            {
                                readSize = iMax;
                            }
                            lSize -= readSize;
                            byte[] buf = new byte[readSize];
                            myStream.Read(buf, 0, readSize);
                            strData += Encoding.Unicode.GetString(buf, 0, readSize);
                        }
                        while (lSize > 0);
                        myStream.Close();
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 将字节从当前缓冲的 IsolatedStorageFileStream 对象复制到数组
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="fileName"></param>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="count"></param>
        public bool ReadStringFromFile(string dirName, string fileName, ref string strData)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(dirName);
            sb.Append("\\");
            sb.Append(fileName);

            return ReadStringFromFile(sb.ToString(), ref strData);
        }

        /// <summary>
        /// 获取剩余空间
        /// </summary>
        /// <returns></returns>
        public long GetAvailableFreeSpace()
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    return store.AvailableFreeSpace;
                }
            }
            catch(Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <returns></returns>
        public long GetFileSize(string fileName)
        {
            try
            {
                if (FileExist(fileName))
                {
                    using (IsolatedStorageFileStream myStream = OpenFileForRead(fileName, FileMode.Open))
                    {
                        long len = myStream.Length;
                        myStream.Close();
                        return len;
                    }
                }
                return 0;
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

        /// <summary>
        /// 重载：获取文件大小
        /// </summary>
        /// <returns></returns>
        public long GetFileSize(string dirName, string fileName)
        {
            try
            {
                if (DirectoryExist(dirName))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(dirName);
                    sb.Append("\\");
                    sb.Append(fileName);
                    return GetFileSize(sb.ToString());
                }
                return 0;
            }
            catch (Exception ex)
            {
                
                throw (ex);
            }
        }

    }
}
